#include <math.h>

#include "sintonia.h"
#include "mainwindow.h"

sintonia* sintonia::instance = NULL;

sintonia::sintonia()
{
    ZN[0] = 1;
    ZN[1] = ZN[2] = 0;
    CHR_sem[0] = 1;
    CHR_sem[1] = CHR_sem[2] = 0;
    CHR_20[0] = 1;
    CHR_20[1] = CHR_20[2] = 0;
    CC[0] = 1;
    CC[1] = CC[2] = 0;
    ITAE_servo[0] = 1;
    ITAE_servo[1] = ITAE_servo[2] = 0;
    ITAE_reg[0] = 1;
    ITAE_reg[1] = ITAE_reg[2] = 0;
}

sintonia::~sintonia()
{
    instance = NULL;
}

sintonia *sintonia::getInstance()
{
    if (instance == NULL)
        instance = new sintonia();
    return instance;
}

void sintonia::calcSintonias() {
    double K = identificacao::getInstance()->ganho;
    double t = identificacao::getInstance()->constTempo;
    double TM = identificacao::getInstance()->tempoMorto;

    ZN[0] = 1.2*(t/(K*TM));
    ZN[1] = 2*TM;
    ZN[2] = 0.5*TM;

    CHR_sem[0] = 0.6*(t/(K*TM));
    CHR_sem[1] = t;
    CHR_sem[2] = 0.5*TM;

    CHR_20[0] = 0.95*(t/(K*TM));
    CHR_20[1] = 1.357*t;
    CHR_20[2] = 0.473*TM;

    CC[0] = (1.35+0.25*(TM/t))*(t/(K*TM));
    CC[1] = TM*( (1.35+0.25*(TM/t))/(0.54+0.33*(TM/t)) );
    CC[2] = (0.5*TM)/(1.35+0.25*(TM/t));

    double A = 0.965;
    double B = -0.850;
    double C = 0.796;
    double D = -0.147;
    double E = 0.308;
    double F = 0.929;

    ITAE_servo[0] = (1/K)*(A*pow((TM/t),B));
    ITAE_servo[1] = t/(C+D*(TM/t));
    ITAE_servo[2] = t*(E*pow((TM/t),F));

    A = 1.357;
    B = -0.947;
    C = 0.842;
    D = -0.738;
    E = 0.381;
    F = 0.995;

    ITAE_reg[0] = (1/K)*(A*pow((TM/t),B));
    ITAE_reg[1] = t/(C*pow((TM/t),D));
    ITAE_reg[2] = t*(E*pow((TM/t),F));

    printf("Ziegler Nichols: [%f,%f,%f]\n", ZN[0],ZN[1],ZN[2]);
    printf("CHR: [%f,%f,%f]\n", CHR_sem[0],CHR_sem[1],CHR_sem[2]);
    printf("CC: [%f,%f,%f]\n", CC[0],CC[1],CC[2]);
    printf("ITAE: [%f,%f,%f]\n", ITAE_servo[0],ITAE_servo[1],ITAE_servo[2]);
}

/*
void sintonia::setTime(int time) {
    ISEPoints.clear();
    IAEPoints.clear();
    ITAEPoints.clear();
    ITSEPoints.clear();
    VYPoints.clear();
    VSCPoints.clear();
    intCont = ISE = IAE = ITAE = ITSE = desvioY = desvioControl = intY = K = 0;
    printf("START INDICES %f\n",intCont);
    tempIndices = time + 0.1;
    running = true;
}
*/
